/**
 * 加密工具类方法
 * @author
 * @version 2018-04-21
 */
import CryptoJS from "crypto-js";

const _processKey = srcKey => {
  const keyLen = 8;
  const srcKeyLen = srcKey.length;
  if (srcKeyLen > keyLen) {
    srcKey = srcKey.substr(0, keyLen);
  } else {
    const paddLen = keyLen - srcKeyLen;
    for (let i = 0; i < paddLen; i += 1) {
      srcKey += "0";
    }
  }
  return CryptoJS.enc.Utf8.parse(srcKey);
};

/**
 * 加密方法
 * @param { String } content
 * @param { String } srcKey
 */
export const encrypt = (content, srcKey) => {
  if (!srcKey) {
    return "";
  }
  const key = _processKey(srcKey);
  const plainText = CryptoJS.enc.Utf8.parse(content);
  const encryptStr = CryptoJS.DES.encrypt(plainText, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
  return encryptStr.toString();
};

/**
 * 解密
 * @param {*} content
 * @param {*} srcKey
 */
export const decrypt = (content, srcKey) => {
  if (!srcKey) {
    return "";
  }
  const key = _processKey(srcKey);
  const ciphertext = CryptoJS.enc.Base64.parse(content);
  let decryptStr = CryptoJS.DES.decrypt(
    {
      ciphertext
    },
    key,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }
  );
  // decryptStr = decryptStr.toString();
  // console.log(decryptStr);
  // const result: string[] = [];
  // for (let index = 0; index < decryptStr.length; index += 2) {
  //   const char = decryptStr[index] + decryptStr[index + 1];
  //   result.push(String.fromCharCode(parseInt(char, 16)));
  // }
  return decryptStr.toString(CryptoJS.enc.Utf8);
};
